"""Config flow for voice_assistant_contro integration."""
from __future__ import annotations

import logging
from typing import Any

import aiohttp
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import selector
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import config_validation as cv
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN

from .const import (
    DOMAIN,
    API_LOGIN_PATH,
    SERVER_HOST,
    CONF_USERNAME,
    CONF_PASSWORD,
    CONF_ENTITIES,
    ALLOWED_ENTITY_DOMAINS,
    REGISTER_URL,
)

_LOGGER = logging.getLogger(__name__)

STEP_USER_DATA_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_USERNAME): str,
        vol.Required(CONF_PASSWORD): str,
    }
)

async def validate_auth(hass: HomeAssistant, username: str, password: str) -> dict | bool:
    """验证用户名和密码是否有效，返回用户信息或False。"""
    session = async_get_clientsession(hass)
    
    try:
        async with session.post(
            f"{SERVER_HOST}{API_LOGIN_PATH}",
            json={
                "username": username,
                "password": password,
            },
        ) as response:
            if response.status != 200:
                return False
            result = await response.json()
            if "success" in result and result["success"]:
                return result  # 返回完整的结果对象
            return False
            
    except aiohttp.ClientError:
        return False

class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow for voice_assistant_contro."""

    VERSION = 1

    def __init__(self) -> None:
        """Initialize the config flow."""
        self.auth_info: dict[str, Any] = {}

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> FlowResult:
        """Handle the initial step."""
        if self._async_current_entries():
            return self.async_abort(reason="already_configured")

        errors: dict[str, str] = {}

        if user_input is not None:
            try:
                # 验证认证信息
                auth_result = await validate_auth(self.hass, user_input[CONF_USERNAME], user_input[CONF_PASSWORD])
                if auth_result:
                    self.auth_info = user_input
                    self.auth_info["user_data"] = auth_result  # 保存用户数据
                    return await self.async_step_select_entities()
                errors["base"] = "invalid_auth"
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unexpected exception")
                errors["base"] = "unknown"

        return self.async_show_form(
            step_id="user",
            data_schema=STEP_USER_DATA_SCHEMA,
            errors=errors,
            description_placeholders={
                "register_url": REGISTER_URL
            }
        )

    async def async_step_select_entities(self, user_input=None):
        """让用户选择要监控的实体。"""
        if user_input is not None:
            return await self.async_step_success()
        # 获取所有实体
        entities = {}
        registry = er.async_get(self.hass)
        
        # 只添加允许的实体类型
        for entity_id in registry.entities:
            domain = entity_id.split('.')[0]
            if domain in ALLOWED_ENTITY_DOMAINS:
                state = self.hass.states.get(entity_id)
                if state:
                    friendly_name = state.attributes.get("friendly_name", entity_id)
                    # 使用 friendly_name 作为显示名称，但值仍然是 entity_id
                    entities[entity_id] = f"{friendly_name} ({entity_id})"

        return self.async_show_form(
            step_id="select_entities",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_ENTITIES): cv.multi_select(entities),
                }
            ),
            description_placeholders={
                "allowed_types": "、".join([
                    "灯" if d == "light" else
                    "空调" if d == "climate" else
                    "窗帘" if d == "cover" else
                    "开关" if d == "switch" else d
                    for d in ALLOWED_ENTITY_DOMAINS
                ])
            }
        )
            
    async def async_step_success(self, user_input=None):
        """显示配置成功页面。"""
        if user_input is not None:
            return self.async_create_entry(
                title=self.auth_info[CONF_USERNAME],
                data={
                    **{k: v for k, v in self.auth_info.items() if k != "user_data"},  # 排除user_data
                    #CONF_ENTITIES: user_input[CONF_ENTITIES],
                }
            )
        user_data = self.auth_info.get("user_data", {})
        subdomain = user_data.get("subdomain", "")
        remote_url = f"http://{subdomain}.hasskit.com" if subdomain else "未获取到子域名"
        return self.async_show_form(
            step_id="success",
            data_schema=vol.Schema({}),
            description_placeholders={
                "remote_url": remote_url
            }
        )
        
       
    @staticmethod
    @callback
    def async_get_options_flow(config_entry):
        """获取选项流程。"""
        return VoiceAssistantControlOptionsFlow(config_entry)

class VoiceAssistantControlOptionsFlow(config_entries.OptionsFlow):
    """处理语音助手控制集成的配置选项。"""

    def __init__(self, config_entry):
        """初始化选项流程。"""
        self.config_entry = config_entry

    async def async_step_init(self, user_input=None):
        """管理语音助手控制选项。"""
        if user_input is not None:
            # 验证数据格式
            if not isinstance(user_input, dict):
                return self.async_abort(reason="invalid_data_format")
            
            if CONF_ENTITIES not in user_input:
                return self.async_abort(reason="missing_entities")
            
            if not isinstance(user_input[CONF_ENTITIES], list):
                return self.async_abort(reason="invalid_entities_format")
            
            # 验证实体ID格式
            for entity_id in user_input[CONF_ENTITIES]:
                if not isinstance(entity_id, str) or '.' not in entity_id:
                    return self.async_abort(reason="invalid_entity_id")
            
            return self.async_create_entry(data=user_input)

        # 获取当前配置的实体（优先从选项获取，否则从数据获取）
        current_entities = self.config_entry.options.get(CONF_ENTITIES, self.config_entry.data.get(CONF_ENTITIES, []))
        
        # 获取所有可用实体
        entities = {}
        registry = er.async_get(self.hass)
        
        # 只添加允许的实体类型
        for entity_id in registry.entities:
            domain = entity_id.split('.')[0]
            if domain in ALLOWED_ENTITY_DOMAINS:
                state = self.hass.states.get(entity_id)
                if state:
                    friendly_name = state.attributes.get("friendly_name", entity_id)
                    # 使用 friendly_name 作为显示名称，但值仍然是 entity_id
                    entities[entity_id] = f"{friendly_name} ({entity_id})"

        return self.async_show_form(
            step_id="init",
            data_schema=vol.Schema(
                {
                    vol.Required(
                        CONF_ENTITIES,
                        default=current_entities
                    ): cv.multi_select(entities),
                }
            ),
            description_placeholders={
                "allowed_types": "、".join([
                    "灯" if d == "light" else
                    "空调" if d == "climate" else
                    "窗帘" if d == "cover" else
                    "开关" if d == "switch" else d
                    for d in ALLOWED_ENTITY_DOMAINS
                ])
            }
        ) 